<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/8/17
 * Time: 10:39 AM
 */
namespace app\admin\common;

use app\common\event\Tool;
use think\facade\Request;

trait UTool
{
    /**
     * 组装form表单数据
     * @param $title
     * @param $field
     * @param $data
     * @param $action
     * @return array
     */
    public function buildEditFormData($title,$field,$data,$action)
    {
        foreach($field as &$v){
            $_name = $v['name'];
            if($data && isset($data[$_name])){
                $v['value'] = $data[$_name];
            }
            if(empty($v['placeholder'])){
                $v['placeholder'] = '请输入'.$v['label'];
            }
            if(empty($v['type'])){
                $v['type'] = 'text';
            }
        }
        
        return [
            'title'  => $title,
            'field'  => $field,
            'action' => $action?$action:url('edit')
        ];
    }

    /**
     * 上传
     */
    public function imgUpload()
    {
        $res = ['success'=>0,'msg'=>'上传文件为空'];
        $files = request()->file('file');
        if($files){
            $uploadFilePath = [];
            $errors = [];
            foreach($files as $file){
                $info = $file->validate(['size'=>156780])->move( '../public/uploads');
                if($info){
                    $path = '/uploads/'.$info->getSaveName();
                    $uploadFilePath[] = $path;
                }else{
                    $errors[] = $file->getError();
                }
            }
            
            if(empty($errors)){
                $res = ['success'=>1,'msg'=>'上传成功','data'=>$uploadFilePath];
            }else{
                if($uploadFilePath){
                    $res = ['success'=>1,'msg'=>'部分上传成功','data'=>$uploadFilePath,'err'=>$errors];
                }else{
                    $res = ['success'=>0,'msg'=>'上传出错'.implode('<br>',$errors)];
                }
            }
        }
        exit(json_encode($res));
    }

    public function generatorRandomStr()
    {
        $len = Request::get('len',32);
        $str = Tool::gStr($len);
        exit(json_encode(['success'=>1,'data'=>$str]));
    }
}